<template>
  <div class="app-container">
    <!--查询  -->
    <el-row>
      <el-input
        style="width: 200px"
        v-model="tableQuery.nickname"
        placeholder="昵称"
      ></el-input>
      <span style="margin-right: 15px"></span>
      <el-tooltip class="item" content="搜索" placement="top">
        <el-button
          icon="el-icon-search"
          circle
          @click="fetchData(1)"
          v-perm="'b:windUser:page'"
        ></el-button>
      </el-tooltip>
    </el-row>
    <div style="margin-bottom: 30px;"></div>
    <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleCreate" v-perm="'b:user:add'">{{textMap.create}}</el-button>
    <div style="margin-bottom: 30px;"></div>
    <!--列表-->
    <el-table
      style="width: 100%"
      :data="tableData"
      v-loading.body="tableLoading"
      element-loading-text="加载中"
      border
      fit
      highlight-current-row
    >
      <el-table-column prop="id" label="id"></el-table-column>
      <el-table-column prop="name" label="名称"></el-table-column>
      <el-table-column prop="logogram" label="简写"></el-table-column>
      <el-table-column prop="priority" label="优先级"></el-table-column>
      <el-table-column prop="scope" label="范围"></el-table-column>
      <el-table-column prop="createTime" label="创建时间"></el-table-column>
      <el-table-column prop="updataTime" label="更新时间"></el-table-column>
      <el-table-column prop="isActive" label="状态"></el-table-column>
      <el-table-column label="操作" fixed="right" width="150px">
        <template slot-scope="scope">
          <el-tooltip content="编辑" placement="top">
            <el-button @click="handleUpdate(scope.$index,scope.row)" size="mini" type="text">编辑</el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top" v-if="!hasAdminRole(scope.row)">
            <el-button @click="handleDelete(scope.$index,scope.row)" size="mini" type="text">删除</el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-bottom: 30px"></div>
    <!--分页-->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="tablePage.current"
      :page-sizes="[10, 20, 30, 40, 50]"
      :page-size="tablePage.size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="tablePage.total"
    >
    </el-pagination>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="20%">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="120px">

        <el-form-item label="名称" prop="name" v-if="dialogStatus=='create'">
          <el-input v-model="temp.name"></el-input>
        </el-form-item>

        <el-form-item label="简写" prop="logogram">
          <el-input v-model="temp.logogram"></el-input>
        </el-form-item>

        <el-form-item label="优先级" prop="priority">
          <el-input v-model="temp.pwd"></el-input>
        </el-form-item>

        <el-form-item label="范围" prop="scope">
          <el-input v-model="temp.pwd2"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">创建</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import DimenApi from '@/api/dimen'
import { parseTime, resetTemp } from "@/utils";
import { root, confirm, pageParamNames } from "@/utils/constants";
import debounce from "lodash/debounce";

export default {
  name: "users",

  data() {
    return {
      parseTime: parseTime,
      tableLoading: false,
      tableData: [],
      tableQuery: {
        nickname: null,
      },
      dialogFormVisible: false,
      editRolesDialogVisible: false,
      dialogStatus: '',
      textMap:{
        update: '编辑维度',
        create: '添加维度'
      },
      tablePage: {
        current: null,
        pages: null,
        size: null,
        total: null,
      },
      temp: {
        idx: null,
        name: null,
        logogram: null,
        priority: null,
        scope: null,
        create_time: null,
        update_time: null
      },
    };
  },

  created() {
    this.fetchData();
  },

  watch: {
    //延时查询
    // "tableQuery.nickname": debounce(function () {
    //   this.fetchData();
    // }, 500),
  }, //watch

  methods: {
    //分页
    handleSizeChange(val) {
      this.tablePage.size = val;
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.tablePage.current = val;
      this.fetchData();
    },

    hasAdminRole(row){
        if(row && row.roleList){
          return row.roleList.some(role=>role.rval==root.rval)
        }
        return false
      },
    //查询
    fetchData(current) {
      if (current) {
        this.tablePage.current = current;
      }
      this.tableLoading = true;
      DimenApi.page(this.tableQuery, this.tablePage).then((res) => {
        this.tableData = res.data.page.records;
        this.tableLoading = false;
        pageParamNames.forEach((name) =>
          this.$set(this.tablePage, name, res.data.page[name])
        );
      });
    },

    //更新
    handleUpdate(idx, row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.idx = idx
      this.temp.name = null
      this.temp.logogram = null
      this.temp.priority = null
      this.temp.scope = null
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => this.$refs['dataForm'].clearValidate())
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) return
        const tempData = Object.assign({}, this.temp)//copy obj
        userApi.updateUser(tempData).then(res => {
          tempData.updated = res.data.updated
          this.tableData.splice(tempData.idx, 1, tempData)
          this.dialogFormVisible = false
          this.$message.success("更新成功")
        })
      })
    },


    //更新用户的角色
    handleUpdateUserRoles(idx, row) {

      // 显示用户的角色
      this.updateUserRolesData = {
        idx: idx,
        uid: row.uid,
        rids: row.roleList.map(role=>role.rid)
      }
      // 显示弹窗
      this.editRolesDialogVisible = true
    },

    checkUpdateUserRolesData() {
      const noRolesSelected = this.updateUserRolesData && this.updateUserRolesData.rids && this.updateUserRolesData.rids.length ==0;
      if(noRolesSelected){
        this.$confirm('当前没有选中任何角色，会清除该用户已有的角色, 是否继续?', '提示', confirm).then(() => {
          this.invokeUpdateUserRolesApi()
        }).catch(() => {
          this.$message("已取消编辑用户角色");
        });
      }else{
        this.invokeUpdateUserRolesApi()
      }
    },

    invokeUpdateUserRolesApi(){
      userApi.updateUserRoles(this.updateUserRolesData).then(res => {
        let newRoles = this.updateUserRolesData.rids.map(rid=>{
          let rname = this.roleMap.get(rid);
          if(rname) return {rid,rname}
        })
        this.tableData[this.updateUserRolesData.idx].roleList = newRoles
        this.editRolesDialogVisible = false
        this.$message.success("更新成功")
      })
    },

    //删除
    handleDelete(idx, row) {
      this.$confirm('您确定要永久删除该用户？', '提示', confirm).then(() => {
        userApi.deleteUser({uid: row.uid}).then(res => {
          this.tableData.splice(idx, 1)
          --this.tablePage.total
          this.dialogFormVisible = false
          this.$message.success("删除成功")
        })
      }).catch(() => {
        this.$message.info("已取消删除")
      });

    },

    //新增
    handleCreate() {
      resetTemp(this.temp)
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) return;
        userApi.addUser(this.temp).then((res) => {
          this.temp.uid = res.data.uid;//后台传回来新增记录的id
          this.temp.created = res.data.created;//后台传回来新增记录的时间
          this.temp.roleList = []
          this.tableData.unshift(Object.assign({},this.temp))
          ++this.tablePage.total
          this.dialogFormVisible = false
          this.$message.success("添加成功")
        })
      })
    }
  },
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.role-checkbox {
  margin-left: 0px;
  margin-right: 15px;
}
</style>
